package xy.rabbitmq.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static xy.rabbitmq.conf.DirectRabbitConfig.DIRECT_Exchange;
import static xy.rabbitmq.conf.DirectRabbitConfig.DIRECT_QUEUE_Exchange_KEY;
import static xy.rabbitmq.conf.FaoutRabbitConfig.FAOUT_EXCHANGE;
import static xy.rabbitmq.conf.TopicRabbitConfig.*;

@RestController
public class MqController {

    /**
     * 使用RabbitTemplate,这提供了接收/发送等等方法
     */
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 直连交换机
     *
     * @return
     */
    @GetMapping("/sendDirectMessage")
    public String sendDirectMessage() {
        String messageData = "test message, hello!";
        Map<String, Object> map = getMessage(messageData);
        //将消息携带绑定键值：TestDirectRouting 发送到交换机TestDirectExchange
        rabbitTemplate.convertAndSend(DIRECT_Exchange, DIRECT_QUEUE_Exchange_KEY, map);
        return "ok";
    }


    /**
     * 主题交换机1 发送路由键  MAN_QUEUE
     *
     * @return
     */
    @GetMapping("/sendTopicMessage1")
    public String sendTopicMessage1() {
        String messageData = "message: M A N ";
        Map<String, Object> manMap = getMessage(messageData);
        rabbitTemplate.convertAndSend(TOPIC_Exchange, MAN_QUEUE, manMap);
        return "ok";
    }

    /**
     * 主题交换机2 发送路由键  WO_MAN_QUEUE
     *
     * @return
     */
    @GetMapping("/sendTopicMessage2")
    public String sendTopicMessage2() {
        String messageData = "message: woman is all ";
        Map<String, Object> womanMap = getMessage(messageData);
        rabbitTemplate.convertAndSend(TOPIC_Exchange, WO_MAN_QUEUE, womanMap);
        return "ok";
    }


    /**
     * 扇形交换机
     * @return
     */
    @GetMapping("/sendFanoutMessage")
    public String sendFanoutMessage() {
        String messageData = "message: testFanoutMessage ";
        Map<String, Object> map = getMessage(messageData);
        rabbitTemplate.convertAndSend(FAOUT_EXCHANGE, null, map);
        return "ok";
    }


    public static Map<String, Object> getMessage(String messageData) {
        String messageId = String.valueOf(UUID.randomUUID());
        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        return map;
    }


}
